package Secondpagh;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.gyf.immersionbar.ImmersionBar;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import SHU.water2.R;
import ThirdPagh.pumpList;
import utils.Auth;

import static SHU.water2.loginin.connection;
import static SHU.water2.loginin.nickname;

public class pumpMap extends AppCompatActivity implements View.OnClickListener {

    private String targetUrl = "https://81.68.81.12/gaodemap.html";
    public WebSettings webSetting;
    public WebView webView;
    public ImageButton save;
    public ImageButton location;
    private long timeout = 5000;
    private Handler mHandler = new Handler();
    private Timer timer;
    private int openSite = 0;
    private int closeSite = 0;
    private int fallSite = 0;
    private Handler handler;
    public static String siteState;

    public static Bitmap drawingCache;
    public String picDate;

    private LocationManager lm;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationListener mLocationListener;

    //@SuppressLint("HandlerLeak")
    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface", "HandlerLeak"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pumpmap);
        ImmersionBar.with(this).statusBarColor(R.color.color).fitsSystemWindows(true).init();
        Button open = findViewById(R.id.open);
        Button close = findViewById(R.id.close);
        Button fall = findViewById(R.id.fall);
        handler = new Handler() {
            //接收消息
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                open.setText("  开 （" + openSite + "）");
                close.setText("  关 （" + closeSite + "）");
                fall.setText("  掉线 （" + fallSite + "）");
            }
        };

        location = findViewById(R.id.location);
        save = findViewById(R.id.save);
        save.setVisibility(View.GONE);

        lm = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
        boolean locationPower = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (locationPower) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                // 没有权限，申请权限。
                //Toast.makeText(this, "请授予应用定位权限", Toast.LENGTH_SHORT).show();
                alertDialog("请授予软件定位权限", 2);

            } else {
                //Toast.makeText(this, "有权限", Toast.LENGTH_SHORT).show();
            }
        } else {
            alertDialog("请打开GPS定位服务", 1);
        }

        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mLocationListener);

        webView = (WebView) findViewById(R.id.mapView);
        mLocationClient.startAssistantLocation(webView);
        initView();
        connect("select * from pump_site");
        click();
    }

    private void connect(String sql) {
        ArrayList<String> L1 = new ArrayList<>();

        //新建线程连接数据库，防止主界面卡死
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Statement statement = connection.createStatement();
                    // 创建用来执行sql语句的对象
                    if (sql.equals("select * from pump_site")) {
                        // 执行sql查询语句并获取查询信息
                        ResultSet rSet = statement.executeQuery(sql);
                        while (rSet.next()) {
                            L1.add(rSet.getString("status"));
                        }

                        for (int i = 0; i < L1.size(); i++) {
                            if (L1.get(i).equals("1")) {
                                openSite++;
                            } else if (L1.get(i).equals("2"))
                                closeSite++;
                            else fallSite++;
                        }

                        Message msg = new Message();
                        handler.sendMessage(msg);
                    }
                    if (sql.startsWith("insert into", 0)) {
                        statement.executeUpdate(sql);
                        Log.i("jj", "success");
                    }

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void alertDialog(String content, int flag) {
        AlertDialog.Builder alertDialogbuilder = new AlertDialog.Builder(this);
        alertDialogbuilder.setTitle("提示");
        alertDialogbuilder.setMessage(content);
        alertDialogbuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (flag == 1)
                    locationSet();
                else if (flag == 2)
                    softwarePower();
                else
                    ViewSnapshot();
            }
        });
        alertDialogbuilder.setNeutralButton("取消", null);
        final AlertDialog alertdialog = alertDialogbuilder.create();
        alertdialog.show();
    }

    public void locationSet() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, 1315);
    }

    public void softwarePower() {
        Intent intent = new Intent();
        intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + this.getPackageName()));
        startActivityForResult(intent, 1315);
    }


    @SuppressLint("SetJavaScriptEnabled")
    public void initView() {
        webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDefaultTextEncodingName("utf-8");
        webSetting.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSetting.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSetting.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSetting.setBuiltInZoomControls(true);
        webSetting.setDisplayZoomControls(false);//隐藏缩放控件
        webSetting.setDomStorageEnabled(true);
        webSetting.setAllowUniversalAccessFromFileURLs(true);
        webSetting.setAllowFileAccess(true);
        webView.setWebViewClient(new WebViewClient() {

            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();  // 接受所有网站的证书
            }

            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                timer.cancel();
                timer.purge();
            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                timer = new Timer();
                TimerTask tt = new TimerTask() {
                    @Override
                    public void run() {
                        /*
                         * 超时后,首先判断页面加载进度,超时并且进度小于100,就执行超时后的动作
                         */
                        mHandler.sendEmptyMessage(0x101);
                        timer.cancel();
                        timer.purge();
                    }
                };
                timer.schedule(tt, timeout, 1);
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            // 处理javascript中的alert   高德地图
            public boolean onJsAlert(WebView view, String url, String message,
                                     final JsResult result) {
                return true;
            }

            // 处理javascript中的confirm
            public boolean onJsConfirm(WebView view, String url,
                                       String message, final JsResult result) {
                return true;
            }

            // 处理定位权限请求
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin,
                                                           GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

        });
        webSetting.setJavaScriptEnabled(true);
        webView.loadUrl(targetUrl);//加载要在setting后，否则输入时无法聚焦
    }


    private void click() {
        findViewById(R.id.location).setOnClickListener(this);
        findViewById(R.id.ret1).setOnClickListener(this);
        findViewById(R.id.save).setOnClickListener(this);
        findViewById(R.id.map).setOnClickListener(this);
        //findViewById(R.id.list).setOnClickListener(this);
        findViewById(R.id.open).setOnClickListener(this);
        findViewById(R.id.close).setOnClickListener(this);
        findViewById(R.id.fall).setOnClickListener(this);
    }

    public void onClick(View v) {
        Intent intent = new Intent();
        LinearLayout calculate = findViewById(R.id.calculate);
        switch (v.getId()) {
            case R.id.ret1:
                mLocationClient.stopAssistantLocation();
                this.finish();
                break;
            case R.id.map:
                save.setVisibility(View.INVISIBLE);
                mLocationClient.stopAssistantLocation();
                location.setVisibility(View.VISIBLE);
                calculate.setVisibility(View.VISIBLE);
                webView.loadUrl(targetUrl);
                break;
            case R.id.save:
                alertDialog("是否结束巡检并保存路径", 3);
                break;
            case R.id.open:
                siteState = "open";
                mLocationClient.stopAssistantLocation();
                intent.setClass(getApplicationContext(), pumpList.class);
                startActivity(intent);
                break;
            case R.id.close:
                siteState = "close";
                intent.setClass(getApplicationContext(), pumpList.class);
                startActivity(intent);
                break;
            case R.id.fall:
                siteState = "fall";
                mLocationClient.stopAssistantLocation();
                intent.setClass(getApplicationContext(), pumpList.class);
                startActivity(intent);
                break;
            case R.id.location:
                mLocationClient.startAssistantLocation(webView);
                save.setVisibility(View.VISIBLE);
                location.setVisibility(View.INVISIBLE);
                calculate.setVisibility(View.INVISIBLE);
                webView.loadUrl("https://81.68.81.12/gaodelocation.html");
                break;
        }
    }

    private void ViewSnapshot() {
        //使控件可以进行缓存
        webView.setDrawingCacheEnabled(true);
        //获取缓存的 Bitmap
        drawingCache = webView.getDrawingCache();
        //复制获取的 Bitmap
        drawingCache = Bitmap.createBitmap(drawingCache);
        //关闭视图的缓存
        webView.setDrawingCacheEnabled(false);
        String picPath = saveBitmap(drawingCache);

        UploadManager uploadManager = new UploadManager();
        uploadManager.put(picPath, picDate, Auth.create("YLUAzQSw-RZjvT-IMEs4HwLgc5lcj40sOFcNV4S1", "zqzl80SmehLT5xDB8Bp24gTCGNwohTh-fre9wzlY").uploadToken("pumpapp"),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        // info.error中包含了错误信息，可打印调试
                        // 上传成功后将key值上传到自己的服务器
                        if (info.isOK()) {
                            String headpicPath = "qstxcjmw2.hd-bkt.clouddn.com/" + key;
                            System.out.println("complete: " + headpicPath);

                            String sql = "insert into history_location values( '" + nickname + "','" + picDate + "', 'qstxcjmw2.hd-bkt.clouddn.com/" + picDate + "')";
                            connect(sql);
                            Toast.makeText(pumpMap.this, "上传成功", Toast.LENGTH_SHORT).show();
                        } else
                            Toast.makeText(pumpMap.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                }, null);
    }

    private String saveBitmap(Bitmap bitmap) {
        //获取需要存储到本地的路径
        File file = new File(Environment.getExternalStorageDirectory(), "/historyLocation/");
        //如果文件夹不存在 就创建文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        picDate = df.format(new Date());
        File path = new File(file, picDate + ".png");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            // compress - 压缩的意思  将bitmap保存到本地文件中
            bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
            //存储完成后需要清除相关的进程
            fileOutputStream.flush();
            fileOutputStream.close();
            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(path);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(uri);
            sendBroadcast(intent);
        } catch (FileNotFoundException e) {
            System.out.println("error:" + e.toString());
        } catch (IOException e) {
            System.out.println("error:" + e.toString());
            //LogUtils.i("error:"+e.toString());
        }
        System.out.println(path.getPath());
        return path.getPath();
    }

}
